package lvjia.site.ai;

import java.io.OutputStream;

import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class Kimi {
    private static final String ENDPOINT = "https://k.mingpixel.site/v1/chat/completions";
    private static final String AUTH_HEADER_NAME = "Authorization";
    private static final String BEARER_PREFIX = "Bearer ";
    public String executeRequest(String userMessage,String key) {
        String model = "silent_search";
        String result = "";

        try {
            URL url = new URL(ENDPOINT);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty(AUTH_HEADER_NAME, BEARER_PREFIX + key);

            //你可以自定义系统级提示，让它更符合你的服务器
            String requestBody = """
                {
                    "model": "%s",
                    "messages": [
                    {
                    "role": "system",
                    "content": "执行联网搜索，默认为minecraft相关内容，玩家在minecraft聊天栏中对话。优先从https://zh.minecraft.wiki 获取内容，因为这是最标准的。若没有提及游戏版本，默认以1.18以上版本为基准。"
                    },
                        {
                            "role": "user",
                            "content":  "%s"
                        }
                    ],
                    "use_search": true,
                    "stream": false
                }
                """.formatted(model, userMessage);

            connection.setDoOutput(true);
            try (OutputStream os = connection.getOutputStream()) {
                os.write(requestBody.getBytes(StandardCharsets.UTF_8));
            }

            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }

                in.close();
                connection.disconnect();

                JsonObject jsonResponse = JsonParser.parseString(content.toString()).getAsJsonObject();
                JsonObject firstChoice = jsonResponse.getAsJsonArray("choices").get(0).getAsJsonObject();
                String messageContent = firstChoice.getAsJsonObject("message").get("content").getAsString();

                result = new String(messageContent.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
            //    MarkdownLinkParser parser = new MarkdownLinkParser();
            //    BaseComponent[] components = parser.parse(result);


            }
        } catch (Exception e) {
            result = "key出错，或服务不可用，请联系管理员切换模型或者修正key！";
        }
        return result;
    }
}
